package J20241102_dichotomy;

/**
 * Created with IntelliJ IDEA.
 * Description: 二分查找
 * 分治
 * User: 王圆豪
 * Date: 2024-11-02
 * Time: 21:55
 */
public class Test_Dichotomy {
    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
        int target = 9;
        System.out.println(arr[binary_search(arr,target)]);
    }
    public static int binary_search(int[] arr, int target){
        int left = 0;
        int right = arr.length;
        while(left <= right){
            int mid = (left + right) / 2;
            if (arr[mid] < target) left = mid + 1;
            else if(arr[mid] > target) right = mid - 1;
            else return mid;
        }
        return -1;
    }
}
